/**
 * 
 */
package com.geekteam.masterenglish.service;

import java.io.IOException;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.geekteam.masterenglish.biz.LessionBiz;
import com.geekteam.masterenglish.entity.DataRequest;
import com.geekteam.masterenglish.entity.Lession;
import com.geekteam.masterenglish.rest.RESTCaller;
import com.geekteam.masterenglish.utils.Constants;
import com.geekteam.masterenglish.utils.Constants.BundleKey;
import com.geekteam.masterenglish.utils.Constants.TypeRequest;
import com.geekteam.masterenglish.utils.JsonUtil;
import com.geekteam.masterenglish.utils.NetworkUtils;
import com.geekteam.masterenglish.utils.Utils;

/**
 * @author MTROL
 *
 */
public class EEService extends IntentService{

	private static final String TAG = "EEService";
	public EEService() {
		super("EEService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int type = intent.getIntExtra(BundleKey.TYPE_REQUEST, -1);
		DataRequest entity = (DataRequest) intent.getSerializableExtra(BundleKey.DATA_REQUEST);
		String url = new String();
		String title =null;
		switch(type){
		case TypeRequest.GET_DETAIL_LESSION:
			url = NetworkUtils.getLinkRequest(Constants.FUNCTION_DETAIL, entity);
			break;
		case TypeRequest.GET_DETAIL_LESSION_MINI:
			url = NetworkUtils.getLinkRequest(Constants.FUNCTION_DETAIL_MINI, entity);
			break;
		case TypeRequest.CACHE:
			url = intent.getStringExtra(BundleKey.URL);
			title = intent.getStringExtra(BundleKey.TITLE);
			try {
				Utils.downloadFile(getApplicationContext(), url, title);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		case TypeRequest.DOWNLOAD:
			url = intent.getStringExtra(BundleKey.URL);
			title = intent.getStringExtra(BundleKey.TITLE);
			String book = intent.getStringExtra(BundleKey.BOOK);
			try {
				Utils.downloadFile(getApplicationContext(), url, title, book);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		default:
			break;
		}
		Log.i(TAG, url);
		String response = RESTCaller.excute(url);		
		if(response!=null){
			Log.i(TAG, response);
			Lession lession = (Lession) JsonUtil.fromJson(response, Lession.class);
			LessionBiz.updateLession(getApplicationContext(), lession);
		}
	}

}
